import { exportQuantityExcelApi, getRentUserList } from '@/services/api';
import { filterEmptyValues } from '@/utils/common';
import { FileSearchOutlined } from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { useLocation } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Button, Spin, Tag, message } from 'antd';
import dayjs from 'dayjs';
import { isEqual } from 'lodash';
import React, { useRef, useState } from 'react';
import { USER_COMMON_COLUMNS } from '../../common';

const Renting: React.FC = () => {
  const actionRef = useRef<ActionType>();
  /* 上传loading */
  const [loading, setLoading] = useState(false);

  const pathName = useLocation()?.pathname;

  console.log('pathName', pathName);

  const { loading: exportLoading, runAsync } = useRequest(
    async (_parames) => {
      return await exportQuantityExcelApi({
        ..._parames,
      });
    },
    {
      manual: true,
    },
  );

  const columns: any = [
    ...USER_COMMON_COLUMNS,
    {
      title: '到期时间',
      dataIndex: 'expiration_time__range',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          const [startTime, endTime] = value;
          return {
            expiration_time__range: [
              dayjs(startTime).format('YYYY-MM-DD HH:mm:ss'),
              dayjs(endTime)
                .add(23, 'hour')
                .add(59, 'minute')
                .add(59, 'second')
                .format('YYYY-MM-DD HH:mm:ss'),
            ],
          };
        },
      },
    },
    {
      title: '商户名称',
      dataIndex: ['mpuser','name'],
      hideInSearch: true,
    },
    {
      title: '用户姓名',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '用户号码',
      dataIndex: 'mobile',
      hideInSearch: true,
    },
    // {
    //   title: '组织名',
    //   dataIndex: 'name_affiliated_organization',
    //   hideInSearch: true,
    // },
    {
      title: '组织编码',
      dataIndex: 'organization_code',
      hideInSearch: true,
    },
    {
      title: '组织类型',
      dataIndex: 'type_organization',
      hideInSearch: true,
    },
    {
      title: '购买套餐',
      dataIndex: 'package_name',
      hideInSearch: true,
      render: (text: any) => {
        return (
          <Tag color="success" bordered={false}>
            {text}
          </Tag>
        );
      },
    },
    {
      title: '发展时间',
      dataIndex: 'registration_time',
      hideInSearch: true,
    },
    {
      title: '剩余天数',
      dataIndex: 'days_remaining',
      hideInSearch: true,
    },
    {
      title: '到期时间',
      dataIndex: 'expiration_time',
      hideInSearch: true,
      valueType: 'date',
    },
    {
      title: '订单金额',
      dataIndex: 'rent',
      hideInSearch: true,
    },
    // {
    //   title: '是否新租',
    //   dataIndex: 'name',
    //   hideInSearch: true,
    //   width: 120,
    // },
    {
      title: '预估分成金额',
      dataIndex: 'reward_amount',
      hideInSearch: true,
    },
  ];

  const formRef = useRef<any>();

  return (
    <Spin spinning={loading} tip="上传文件中，请稍等">
      <ProTable
        bordered
        columns={columns}
        actionRef={actionRef}
        cardBordered
        scroll={{ x: 1600 }}
        request={async (_parame) => {
          const { pageSize, current, ...ret } = _parame;

          const { data } = await getRentUserList({
            page: current,
            size: pageSize,
            filters: JSON.stringify({
              ...filterEmptyValues({
                ...ret,
                equipment_category:
                  pathName === '/user/list-of-single-electric-users'
                    ? '电池'
                    : '0',
              }),
            }),
          });
          return {
            data: data?.list ?? [],
            success: true,
            total: data?.count,
          };
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        formRef={formRef}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          defaultPageSize: 10,
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <Button
            loading={exportLoading}
            key="button"
            icon={<FileSearchOutlined />}
            onClick={async () => {
              /* 获取表格搜索框信息 */

              let _faileName: string = '单电用户清单';
              let _header: any = [
                '商户名称',
                '用户姓名	',
                '用户号码',
                '组织编码',
                '组织类型',
                '购买套餐	',

                '发展时间',
                '剩余天数',
                '到期时间',
                '订单金额',
                '预估分成金额',
              ];

              try {
                await runAsync({
                  filename: _faileName,
                  header: _header,
                  fields: [
                    'merchant',
                    'name',
                    'mobile',
                    'organization_code',
                    'type_organization',
                    'package_name',
                    'registration_time',
                    'days_remaining',
                    'expiration_time',
                    'rent',
                    'reward_amount',
                  ],
                  table: 'journal_bindinglog',
                  filter: {
                    ...filterEmptyValues(formRef.current.getFieldsValue()),
                    // equipment_category: '电池',
                    equipment_category:
                      pathName === '/user/list-of-single-electric-users'
                        ? '电池'
                        : '0',
                        merchant:
                        formRef.current.getFieldsValue()?.merchant__contains,
                  },
                });

                message.success(`文件${_faileName}导出成功`);
              } catch (error) {}
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
      />
    </Spin>
  );
};

export default React.memo(Renting, (prev, next) => isEqual(prev, next));
